package org.study.tk.boot.p6spy;

import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 自定义SQL日志格式
 * 参考 https://cloud.tencent.com/developer/article/2032197
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年04月21日
 */
@Slf4j
public class P6spySqlFormat implements MessageFormattingStrategy {
    /**
     * SQL日志格式化
     *
     * @param connectionId 连接ID
     * @param now          当前时间
     * @param elapsed      花费时间
     * @param category     类别
     * @param prepared     预编译SQL
     * @param sql          最终执行的SQL
     * @param url          数据库连接地址
     * @return java.lang.String
     * @throws
     **/
    @Override
    public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
        String result = "";
        if (StringUtils.isNotBlank(sql)) {
            result = "当前时间：" + now + "，连接信息：" + category + "-" + connectionId + "，SQL耗时：" + elapsed + "ms，执行语句：" + sql.replaceAll("[\\s]+", StringUtils.SPACE) + ";";
            /*Map<String, String> map = new LinkedHashMap<>() {{
                this.put("当前时间", now);
                this.put("连接信息", category + "-" + connectionId);
                this.put("SQL耗时", elapsed + "ms");
                this.put("执行语句", sql.replaceAll("[\\s]+", StringUtils.SPACE));
            }};
            result = JSON.toJSONString(map);*/
        }
        return result;
    }
}
